<template>
  <div class="particulars">
    <!-- NavBar start -->
    <van-nav-bar
      title="文章详情"
      left-text="返回"
      @click-left="$router.back()"
      left-arrow
      fixed
    >
      <template #right>
        <van-icon name="ellipsis" size="18" />
      </template>
    </van-nav-bar>
    <div class="main" v-if="otherConditions === 1">
      <!-- 文章标题start -->
      <h1 class="headline">{{ list.title }}</h1>
      <!-- 发表文章的作者信息 start -->
      <div class="authorInfo">
        <van-cell-group>
          <van-cell>
            <div slot="title">
              <div
                class="authorIcon"
                @click="$router.push(`/user/${list.aut_id}`)"
              >
                <img :src="list.aut_photo" alt="" />
              </div>
              <div class="authorNameAndTime">
                <div class="authorName">{{ list.aut_name }}</div>
                <div class="authorTime">{{ list.pubdate | formatDate }}</div>
              </div>
            </div>
            <div slot="default" class="attention">
              <attention v-model="isAttention" :autID="list.aut_id"></attention>
            </div>
          </van-cell>
        </van-cell-group>
      </div>
      <!-- 文章内容 -->
      <div class="content markdown-body" v-html="list.content" ref="imgRef">
        人生人生人生短短几个秋 content 名称 说明 default 自定义右侧 value 的内容
        title 自定义左侧 title 的内容 label 自定义标题下方 label 的内容 icon
        自定义左侧图标 right-icon 自定义右侧按钮，默认为arrow extra
        自定义单元格最右侧的额外内容
      </div>
    </div>
    <!-- 加载中 -->
    <div class="loading" v-else-if="otherConditions === 2">
      <van-loading size="60px" color="#0094ff" vertical>加载中....</van-loading>
    </div>
    <!-- 找不到  -->
    <div class="cannotFind" v-else-if="otherConditions === 3">
      <van-empty description="文章不存在或者已经被删除" />
    </div>
    <!-- 加载失败 -->
    <div class="mistake" v-else-if="otherConditions === 4">
      <van-empty description="加载失败">
        <van-button round type="danger" class="bottom-button"
          >重新加载</van-button
        >
      </van-empty>
    </div>
    <!-- 评论区 -->
    <div class="commentWrapper" v-if="otherConditions === 1">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell v-for="item in commentlList" :key="item.com_id.toString()">
          <div class="comment">
            <van-cell-group>
              <van-cell>
                <div slot="title">
                  <div class="userIcon">
                    <img :src="item.aut_photo" alt="" />
                  </div>
                  <div class="userNameAndTime">
                    <div class="userName">{{ item.aut_name }}</div>
                  </div>
                </div>
                <div slot="default" class="attention">
                  <van-icon class="toutiao toutiao-dianzan" />
                  {{ item.like_count }}
                </div>
              </van-cell>
            </van-cell-group>
            <div class="text">
              {{ item.content }}
            </div>
            <div class="operation">
              <div class="comment-time">{{ item.pubdate | formatDate }}</div>
              <div class="reply" @click="(isReplyShow = true,replys = item)">
                {{ item.reply_count }}回复
              </div>
               <!-- 评论回复 -->
                <van-popup
                  v-model="isReplyShow"
                  closeable
                  close-icon-position="top-left"
                  position="bottom"
                  :style="{ height: '60%' }"
                >
                  <reply :articleId="demo" :replyDatas="replys" :key="replys.com_id"></reply>
                </van-popup>
            </div>
          </div>
        </van-cell>
      </van-list>
    </div>
    <!-- 操作文章区域 -->
    <div class="bottom">
      <div class="writeComment">
        <input type="text" placeholder="写评论" @focus="isShow = true" />
      </div>
      <div class="B-right">
        <i
          class="toutiao toutiao-dianzan"
          @click="praise"
          :style="{ color: this.list.attitude === 1 ? 'red' : '#000' }"
        ></i>
        <i class="toutiao toutiao-pinglun"
          ><em>{{ totalCount }}</em></i
        >
        <i
          class="toutiao toutiao-shoucang"
          :style="{ color: this.list.is_collected ? 'red' : '#000' }"
          @click="collect"
        ></i>
        <i class="toutiao toutiao-fenxiang"></i>
      </div>
    </div>
    <!-- 评论弹出层 -->
    <comments
      v-model="isShow"
      :artid="this.list.art_id"
      :mycomment="mycomment"
      @sendcomment="updataComment($event)"
    ></comments>
    <!-- 回复弹出层 -->
  </div>
</template>

<script>
import { ImagePreview } from 'vant'
import {
  getParticularsData,
  addCollect,
  deleteCollect,
  addLike,
  deleteLike,
  conmentArticle
} from '@/api/homepage/articleLists.js'
import attention from '@/components/attention.vue'
import Comments from '@/components/comments.vue'
import Reply from '@/components/reply.vue'
export default {
  data () {
    return {
      list: [],
      imgList: [],
      isAttention: null,
      otherConditions: 1, // 1 显示内容 2.显示加载中 3 显示页面找不到 4 显示加载失败 其他 显示评论区
      commentlList: [],
      loading: false,
      finished: false,
      offset: null, // 评论偏移量
      limit: 10, // 评论个数
      totalCount: 0, // 评论总数
      isShow: false,
      mycomment: [],
      isReplyShow: false, // 回复
      replys: {}, // 回复的那个人信息
      demo: this.articleId
    }
  },
  props: ['articleId'],
  created () {
    this.getData()
  },
  mounted () {},
  watch: {},
  methods: {
    // 请求数据
    async getData () {
      this.otherConditions = 2
      try {
        const {
          data: { data: res }
        } = await getParticularsData(this.articleId)
        this.list = res
        console.log(res)
        this.isAttention = res.is_followed
        // console.log(res);
        // 因为DOM渲染需要时间 可以设置一个延迟用于等DOM渲染完毕再进行操作
        setTimeout(() => {
          // 获取图片数据
          const image = this.$refs.imgRef.getElementsByTagName('img')
          // const imageLenght = image.length
          image.forEach((item, index) => {
            this.imgList.unshift(item.src)
            item.onclick = () => {
              ImagePreview({
                images: this.imgList,
                startPosition: index
              })
            }
          })
        }, 10)
        this.otherConditions = 1
      } catch (error) {
        if (error.request.status === 404) {
          this.otherConditions = 3
        } else {
          this.otherConditions = 4
        }
      }
    },
    // 收藏
    async collect () {
      // 当网络不健康或者没往时  展示加载中并禁止点击背景
      // 这个加载中会被后面的$toast覆盖也就会关闭加载中
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '操作中...',
        forbidClick: true // 是否禁止背景点击
      })
      try {
        if (this.list.is_collected) {
          //  取消收藏
          await deleteCollect(this.articleId)
          console.log(this.articleId)
          this.$toast.success('已取消收藏')
        } else {
          // 添加收藏
          await addCollect(this.articleId)
          this.$toast.success('收藏成功')
        }
        this.list.is_collected = !this.list.is_collected
      } catch (error) {
        console.log(error)
        this.$toast.fail('操作失败')
      }
      // 关闭加载中
    },
    // 点赞
    async praise () {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '操作中...',
        forbidClick: true // 是否禁止背景点击
      })
      try {
        if (this.list.attitude === 1) {
          // 取消点赞
          await deleteLike(this.articleId)
          this.list.attitude = -1
          this.$toast.success('我一定会更努力的')
        } else {
          // 点赞
          await addLike(this.articleId)
          this.list.attitude = 1
          this.$toast.success('感谢点赞')
        }
      } catch (error) {
        console.log(error)
        this.$toast.fail('操作失败')
      }
    },
    // 获取评论信息
    async onLoad () {
      // 异步更新数据
      try {
        const parmas = {
          type: 'a',
          source: this.articleId,
          offset: this.offset,
          limit: this.limit
        }
        const {
          data: { data: res }
        } = await conmentArticle(parmas)
        this.commentlList.push(...res.results)
        this.offset = res.last_id
        this.totalCount = res.total_count
        // 加载状态结束
        this.loading = false
        if (res.results) {
          // 数据加载完成
          this.finished = true
        }
      } catch (error) {
        this.loading = false
        console.log(error)
      }
    },
    // 评论
    updataComment (data) {
      this.commentlList.unshift(data)
    }
  },
  components: { attention, Comments, Reply }
}
</script>

<style lang="less" scoped>
@import url(./index.less);
@import url(./github-markdown.css);
</style>
